<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\News\News;
use App\Models\News\NewsClass;
use App\Helper\Build\Build;
class BuildNews extends Command
{
    use SetUserAndGroup;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'build:news';

    protected $play_news_build_key = 'play_news_build';

    protected $limit = 1000;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '计划生成新闻';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->setUserAndGroup();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $data = cache($this->play_news_build_key);
        if(!$data)return '不存在任务';
        if($data['status'] == 2)return '已执行完成';
        $model = new News();
        $data['status'] = 1;
        cache([$this->play_news_build_key=>$data], 30000);
        if(!empty($data['class_id']) && is_array($data['class_id']))
        {
            $ids = [];
            foreach ($data['class_id'] as $key => $value) {
                # code...
                if(!is_null($value) && $value>0)
                {
                    $ids[] = $value;
                }
            }
            if(!empty($ids))$model = $model->whereIn('class_id', $data['class_id']);
            
        }
        $model = $model->where('status', 2)->where('created_at', '>=', $data['start_time'])->where('created_at', '<=', $data['end_time']);
        $num = $model->count();

        if($num > $this->limit)
        {
            $page = ceil($num/$this->limit);
            for ($i=1; $i <= $page; $i++) { 
                # code...
                $list = $model->offset(($i-1)*$this->limit)->limit($this->limit)->get();
                $this->buildList($list);

            }
        }else
        {
            $this->buildList($model->get());
        }
        $data['status'] = 2;
        cache([$this->play_news_build_key=>$data], 30000);

    }


    public function buildList($list)
    {
        if($list->isEmpty())return 'ok';
        $Build = new Build();
        foreach ($list as $key => $value) {
            # code...
            $ret = $Build->news($value);
            echo $ret['msg'].chr(10);
        }
    }
}
